//
//  SHUD.swift
//  niuguwang
//
//  Created by BrightLi on 2021/3/2.
//  Copyright © 2021年 taojinzhe. All rights reserved.
//

import Foundation
import UIKit
import SnapKit

let SWaitTag   = 90000
let SNoDataTag = 90001
let SReloadTag = 90002
let SNoDataCowTag = 90003

class SWaitView:UIView
{
    @objc enum SHUDStyle: Int
    {
        case white
        case drak
    }
    
    // 锁
    private static var _lock=NSRecursiveLock()
    
    public var style:SHUDStyle = .white
    public var text:String?
    
    lazy var alert:UIView = {
        return UIView()
    }()
    
    lazy var box:UIView = {
        var temp = UIView()
        temp.layer.cornerRadius = 8
        temp.backgroundColor =  SUIUtil.colorOf((style == .white ?0xffffff:0x000000),alpha: 0.9)
        return temp
    }()
    
    lazy var ai:UIActivityIndicatorView = {
        var temp = UIActivityIndicatorView()
        temp.style = (style == .white ?.gray:.white)
        temp.startAnimating()
        return temp
    }()
    
    lazy var label:UILabel = {
        var temp = SThemeUtil.label("", color: (style == .white ? 0x2a4159:0xffffff), fontSize: 14)
        temp.textAlignment = NSTextAlignment.center
        temp.text = text ?? ""
        temp.isHidden = (temp.text?.count)!<1
        temp.numberOfLines = 0
        return temp
    }()
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame:CGRect)
    {
        super.init(frame: frame)
        self.tag = SWaitTag
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        setupUI()
    }
    
    private func setupUI()
    {
        if alert.superview != nil
        {
            return
        }
        self.addSubview(alert)
        alert.addSubview(box)
        box.addSubview(ai)
        box.addSubview(label)
        
        let vgap = SFitUtil.fit(14)
        let tgap = SFitUtil.fit(6)
        let hgap = SFitUtil.fit(8)
        let side = SFitUtil.fit(36)
        
        alert.snp.makeConstraints { (make) in
            make.edges.equalTo(0)
        }
        box.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.left.greaterThanOrEqualToSuperview().offset(vgap)
            make.top.greaterThanOrEqualToSuperview().offset(vgap)
            make.width.greaterThanOrEqualTo(side+vgap*2)
        }
        ai.snp.makeConstraints { (make) in
            make.top.equalTo(vgap)
            make.centerX.equalToSuperview()
            make.width.equalTo(side)
            make.height.equalTo(side)
        }
        label.snp.makeConstraints { (make) in
            let text = label.text ?? ""
            if text.isEmpty {
                make.top.equalTo(ai.snp.bottom)
            }else{
                make.top.equalTo(ai.snp.bottom).offset(vgap)
            }
            make.left.equalTo(vgap)
            make.right.equalTo(-vgap)
            make.bottom.equalTo(-vgap)
        }
    }
    deinit{
        waitTask = nil
    }
}

class SNoDataView:UIView
{
    lazy var icon:UIImageView = {
        return UIImageView(image: UIImage(named:"all_pic_note_gray"))
    }()
    
    lazy var title:UILabel = {
        let temp = SThemeUtil.label(YMBridging.kLanguage("status_empty"), color: 0x8997a5, fontSize: 14)
        temp.textAlignment = NSTextAlignment.center;
        return temp
    }()
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame:CGRect)
    {
        super.init(frame: frame)
        self.tag = SNoDataTag
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        setupUI()
    }
    
    private func setupUI()
    {
        if icon.superview != nil
        {
            return
        }
        self.addSubview(icon)
        self.addSubview(title)
        let gap = SFitUtil.fit(15)
        icon.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-gap)
            make.width.equalTo(SFitUtil.fit(75))
            make.height.equalTo(SFitUtil.fit(55))
        }
        title.snp.makeConstraints { (make) in
            make.top.equalTo(icon.snp.bottom).offset(gap)
            make.left.equalTo(gap)
            make.right.equalTo(-gap)
        }
    }
}

class SReloadView:UIView
{
    var onReload : ChangeBlock?
    lazy var hot:UIView = {
        return UIView()
    }()
    
    lazy var icon:UIImageView = {
        return UIImageView(image: UIImage(named:"tools_disnet_icon"))
    }()
    
    lazy var title:UILabel = {
        let temp = SThemeUtil.label("点击重新加载", color: 0x8997a5, fontSize: 14)
        temp.textAlignment = NSTextAlignment.center;
        return temp
    }()
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame:CGRect)
    {
        super.init(frame: frame)
        self.tag = SReloadTag
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        setupUI()
    }
    
    private func setupUI()
    {
        if hot.superview != nil
        {
            return
        }
        self.addSubview(hot)
        hot.addSubview(icon)
        hot.addSubview(title)
        hot.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
        let gap = SFitUtil.fit(15)
        icon.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(gap)
            make.left.equalTo(gap)
            make.right.equalTo(-gap)
            make.size.equalTo(SFitUtil.fitSize(90,height:CGFloat(70))).priority(.high)
        }
        title.snp.makeConstraints { (make) in
            make.top.equalTo(icon.snp.bottom).offset(gap)
            make.left.equalTo(gap)
            make.right.equalTo(-gap)
            make.bottom.equalTo(-gap).priority(.low)
        }
        hot.s_clickBlock {[unowned self] (tap:UITapGestureRecognizer ) in
            if let block = self.onReload {
                block()
            }
        }
    }
}

@objcMembers public class SHUD:NSObject
{
    public static var isFull:Bool=false
    
    static var screenTask:STask?
    static var alertView:UIView?
    
    public static var enabled:Bool=true
    
    // 默认延迟0.5秒显示菊花
    dynamic public class func showWait(_ target:UIView)
    {
        showWait(target,text:"",afterShow:0.5)
    }
    // 默认延迟0.5秒显示菊花
    dynamic public class func showThemeWait(_ target:UIView)
    {
        showWait(target,text:"",afterShow:0.5)
    }
    dynamic public class func showWait(_ target:UIView,text:String)
    {
        showWait(target,text:text,afterShow:0.5)
    }
    dynamic public class func showWait(_ target:UIView,text:String,afterShow:TimeInterval)
    {
        hide(target)
        target.waitTask = STimeUtil.delay(afterShow, task: {
            let state = SWaitView()
            state.text = text
            state.style = .white
            target.addSubview(state)
            state.snp.makeConstraints { (make) in
                make.edges.equalTo(0)
            }
            STimeUtil.delay(5, task: {
                hide(target)
            })
        })
    }
    
    dynamic public class func showDarkWait(_ target:UIView)
    {
        showDarkWait(target,text:"",afterShow:0.5)
    }
    
    dynamic public class func showDarkWait(_ target:UIView,text:String)
    {
        showDarkWait(target,text:text,afterShow:0.5)
    }
    
    dynamic public class func showDarkWait(_ target:UIView,text:String,afterShow:TimeInterval)
    {
        hide(target)
        target.waitTask = STimeUtil.delay(afterShow, task: {
            let state = SWaitView()
            state.text = text
            state.style = .drak
            target.addSubview(state)
            state.snp.makeConstraints { (make) in
                make.edges.equalTo(0)
            }
        })
    }
    
    dynamic public class func showNoData(_ target:UIView?)
    {
        showNoData(target,text:YMBridging.kLanguage("status_empty"))
    }
    
    dynamic public class func showNoData(_ target:UIView?,text:String)
    {
        showNoData(target,text:text,offsetY:0)
    }
    
    dynamic public class func showNoData(_ target:UIView?,text:String,offsetY:CGFloat)
    {
        if target==nil{
            return
        }
        hide(target)
        let state = SNoDataView()
        state.title.text=text;
        target!.insertSubview(state, at: 0)
        state.snp.makeConstraints { (make) in
            make.top.equalTo(0)
            make.left.right.equalTo(0)
            make.bottom.equalTo(offsetY)
        }
    }
    
    dynamic public class func showReload(_ target:UIView,onReload:@escaping (() -> ()))
    {
        hide(target)
        let state = SReloadView()
        state.onReload = onReload
        target.insertSubview(state, at: 0)
        state.snp.makeConstraints { (make) in
            make.edges.equalTo(0)
        }
    }
    
    dynamic public class func showInfo(_ text:String)
    {
        if text.count<1{
            return
        }
        showInfo(text,afterHide:1.5)
    }
    
    dynamic public class func showInfo(_ text:String,_ isHP:Bool)
    {
        if text.count<1{
            return
        }
        showInfo(text,afterHide:1.5,isHP)
    }
    dynamic public class func showInfo(_ text:String,afterHide:TimeInterval,_ isHP:Bool)
    {
        if !enabled{
            return
        }
        hide()
        screenInfo(text,isHP)
        screenTask = STimeUtil.delay(afterHide, task: {
            hide()
        })
    }
    private class func screenInfo(_ text:String,_ isHP:Bool)
    {
        let window = SJumpUtil.topWindow()
        let alert=UIView()
        alert.backgroundColor =  UIColor.clear
        alert.isUserInteractionEnabled = false
        
        let box = UIView()
        box.layer.cornerRadius = 9
        box.backgroundColor =  SUIUtil.colorOf(0x000000,alpha: 0.9)
        
        let label=UILabel()
        label.text = text
        label.numberOfLines = 0
        label.font = SFitUtil.fitFont(14)
        label.textAlignment = NSTextAlignment.left
        label.textColor = UIColor.white
        
        box.addSubview(label)
        alert.addSubview(box)
        
        window.addSubview(alert)
        
        let side = SFitUtil.fit(36)
        var size = SFitUtil.sizeOf(label,width:ScreenWidth-SFitUtil.fit(30))
        let gap = SFitUtil.fit(12)

        if size.width < side{
            size.width = side
        }
        if isHP{
            alert.frame = CGRect(x:0,y:0,width:ScreenHeight,height:ScreenWidth)
            alert.center = CGPoint(x:ScreenWidth/2,y:ScreenHeight/2);
            alert.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2);
        }else{
            alert.frame = CGRect(x:0,y:0,width:ScreenWidth,height:ScreenHeight)
        }
        label.snp.makeConstraints { (make) in
            make.size.equalTo(size)
        }
        box.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.top.equalTo(label.snp.top).offset(-gap)
            make.left.equalTo(label.snp.left).offset(-gap)
            make.right.equalTo(label.snp.right).offset(gap)
            make.bottom.equalTo(label.snp.bottom).offset(gap)
        }
        alertView = alert
    }
    dynamic public class func showInfo(_ text:String,afterHide:TimeInterval)
    {
        if !enabled{
            return
        }
        hide()
        screenInfo(text)
        screenTask = STimeUtil.delay(afterHide, task: {
            hide()
        })
    }
    
    private class func screenInfo(_ text:String)
    {
        let window = SJumpUtil.topWindow()
        
        let alert=UIView()
        alert.backgroundColor =  UIColor.clear
        alert.isUserInteractionEnabled = false
        
        let box = UIView()
        box.layer.cornerRadius = 9
        box.backgroundColor =  SUIUtil.colorOf(0x000000,alpha: 0.9)
        
        let label=UILabel()
        label.text = text
        label.numberOfLines = 0
        label.font = SFitUtil.fitFont(14)
        label.textAlignment = NSTextAlignment.left
        label.textColor = UIColor.white
        
        box.addSubview(label)
        alert.addSubview(box)
        
        window.addSubview(alert)
        
        let side = SFitUtil.fit(36)
        var size = SFitUtil.sizeOf(label,width:ScreenWidth-SFitUtil.fit(30))
        let gap = SFitUtil.fit(12)
        
        if size.width < side{
            size.width = side
        }
        if isFull{
            alert.frame = CGRect(x:0,y:0,width:ScreenHeight,height:ScreenWidth)
            alert.center = CGPoint(x:ScreenWidth/2,y:ScreenHeight/2);
            alert.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2);
        }else{
            alert.frame = CGRect(x:0,y:0,width:ScreenWidth,height:ScreenHeight)
        }
        label.snp.makeConstraints { (make) in
            make.size.equalTo(size)
        }
        box.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.top.equalTo(label.snp.top).offset(-gap)
            make.left.equalTo(label.snp.left).offset(-gap)
            make.right.equalTo(label.snp.right).offset(gap)
            make.bottom.equalTo(label.snp.bottom).offset(gap)
        }
        alertView = alert
    }
    
    dynamic public class func showScreenWait(_ text:String)
    {
        showScreenWait(text, afterShow: 0.5)
    }
    
    dynamic public class func showScreenWait(_ text:String,afterShow:TimeInterval)
    {
        hide()
        screenTask = STimeUtil.delay(afterShow, task: {
            screenWait(text)
        })
    }
    
    //加载数据量大接口，延时加载遇到数据返回后显示的问题，增加一个立即调用。
    dynamic public class func showScreenNow(_ text:String)
    {
        screenWait(text)
    }
    
    private class func screenWait(_ text:String)
    {
        let window = UIApplication.shared.keyWindow!
        let alert=UIView()
        alert.backgroundColor =  UIColor.clear
        alert.isUserInteractionEnabled = false
        
        let box = UIView()
        box.layer.cornerRadius = 9
        box.backgroundColor = SUIUtil.colorOf(0x000000,alpha:0.9)
        let ai = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge)
        ai.startAnimating()
        box.addSubview(ai)
        
        let label=UILabel()
        label.text = text
        label.numberOfLines = 0
        label.font = SFitUtil.fitFont(14)
        label.textAlignment = NSTextAlignment.center
        label.textColor = UIColor.white
        
        box.addSubview(label)
        alert.addSubview(box)
        window.addSubview(alert)
        
        let vgap = SFitUtil.fit(14)
        let tgap = SFitUtil.fit(6)
        let hgap = SFitUtil.fit(8)
        let side = SFitUtil.fit(36)
        let size = SFitUtil.sizeOf(label)
        
        let height = vgap + side + tgap + size.height + vgap
        let width = max( hgap + size.width + hgap, height)
        
        alert.snp.makeConstraints { (make) in
            make.edges.equalTo(0)
        }
        box.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalTo(width)
            make.height.equalTo(height)
        }
        ai.snp.makeConstraints { (make) in
            make.top.equalTo(vgap)
            make.centerX.equalToSuperview()
            make.width.equalTo(side)
            make.height.equalTo(side)
        }
        label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-vgap)
            make.size.equalTo(size)
        }
        alert.s_clickBlock { (tap) in
        }
        alertView = alert
    }
    
    dynamic public class func hide(_ target:UIView?)
    {
        if target == nil
        {
            return
        }
        if let task = target!.waitTask{
            STimeUtil.cancel(task)
            target!.waitTask = nil
        }
        if let state:SWaitView = target!.viewWithTag(SWaitTag) as? SWaitView
        {
            state.removeFromSuperview()
        }
        if let state:SNoDataView = target!.viewWithTag(SNoDataTag) as? SNoDataView
        {
            state.removeFromSuperview()
        }
        if let state:SReloadView = target!.viewWithTag(SReloadTag) as? SReloadView
        {
            state.removeFromSuperview()
        }
    }
    
    dynamic public class func hide()
    {
        if screenTask != nil{
            STimeUtil.cancel(screenTask!)
            screenTask = nil
        }
        if alertView != nil{
            if alertView!.superview != nil{
                alertView?.removeFromSuperview()
            }
            alertView=nil
        }
    }
}
